package meiyunting.shiwuzhaoling_gatway.config;

import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import zipkin2.reporter.Sender;
import zipkin2.reporter.brave.AsyncZipkinSpanHandler;
import zipkin2.reporter.okhttp3.OkHttpSender;

/**
 * Zipkin配置类
 * 提供容错处理
 */
@Slf4j
@Configuration
public class ZipkinConfig {

    /**
     * 自定义Zipkin发送器，添加异常处理
     */
    @Bean
    public Sender zipkinSender() {
        return OkHttpSender.newBuilder()
                .endpoint("http://localhost:9411/api/v2/spans")
                .compressionEnabled(true)  // 启用压缩
                .messageMaxBytes(5 * 1024 * 1024)  // 最大消息大小
                .build();
    }

    /**
     * 自定义SpanHandler，添加错误处理
     */
    @Bean
    public SpanHandler customSpanHandler() {
        return new SpanHandler() {
            @Override
            public boolean end(TraceContext context, MutableSpan span, Cause cause) {
                try {
                    if (cause == Cause.ABANDONED) {
                        log.warn("跟踪被放弃: {}", context.traceIdString());
                    }
                    return true;
                } catch (Exception e) {
                    log.error("处理跟踪数据时发生错误", e);
                    return false;
                }
            }
        };
    }
} 